package com.hfh.server.netty_server;

import com.hfh.server.netty_server.coder.NettyMessageDecoder;
import com.hfh.server.netty_server.coder.NettyMessageEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;


/**
 * @Author lxh
 * @Date 2019/5/7 15:16
 * @Description Netty服务端消息处理Handler初始化
 */

@Component
public class NettyServerStringProtocolInitalizer extends ChannelInitializer<SocketChannel> {


    /**
     * 编码器解码器链配置
     * @param socketChannel
     */
    @Override
    protected void initChannel(SocketChannel socketChannel) {
        ChannelPipeline pipeline = socketChannel.pipeline();
//        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
//        pipeline.addLast("decoder", new StringDecoder());  //字符串解码器
//        pipeline.addLast("encoder", new StringEncoder());  //字符串编码器
        //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
        //因为服务端设置的超时时间要大于客户端的超时时间
        pipeline.addLast( new IdleStateHandler(NettyConfig.NETTY_SERVER_READER_IDLE_TME_TIMES, 0, NettyConfig.NETTY_SERVER_ALL_IDLE_TME_TIMES, TimeUnit.SECONDS)); //心跳检测机制
        pipeline.addLast("decoder", new NettyMessageDecoder());  //实体类解码器
        pipeline.addLast("encoder", new NettyMessageEncoder());  //实体类编码器
        pipeline.addLast("handler", new ServerHandler());  //业务handler
    }
}
